#!/usr/bin/env python
# -*- coding: utf-8 -*-
# datetime: 3/12/2023 下午7:10
# Author: name
# File: function_api.py
# ide: PyCharm
# description:
from datetime import datetime
from typing import List

from fastapi import APIRouter, HTTPException, Query

from backend.app.models.function_model import FunctionModel, FunctionOut, FunctionIn, FunctionPage
from backend.app.utils.response_tepmlate import ResponseCode

function_router = APIRouter(prefix="/function", tags=["内置函数"])


# 定义 API 路由
@function_router.post("/add")
async def create_function(function: FunctionIn):
    select_function = await FunctionModel.filter(en_name=function.en_name).first()
    if select_function:
        return ResponseCode(function.en_name).response_409()
    else:
        await FunctionModel.create(
            zh_name=function.zh_name,
            en_name=function.en_name,
            content=function.content,
            params=function.params,
            created_at=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            updated_at=datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        )
        return ResponseCode(function.en_name).response_add()


# 获取内置列表（分页查询）
@function_router.get("/page", response_model=FunctionPage)
async def get_function_page_list(
        page: int = Query(1, ge=1),
        size: int = Query(10, ge=1, le=100),
        zh_name: str = Query(None, min_length=0)
):
    skip = (page - 1) * size
    query = FunctionModel.all()
    if zh_name:
        query = query.filter(zh_name__icontains=zh_name)
    total = await query.count()
    functions = await query.offset(skip).limit(size).values()
    return FunctionPage(total=total, page_size=size, current_page=page, search_key=zh_name, results=functions)


@function_router.get("/list", response_model=List[FunctionOut])
async def read_function_list():
    return await FunctionModel.all()


@function_router.get("/{function_id}", response_model=FunctionOut)
async def get_function(function_id: int):
    function = await FunctionModel.filter(id=function_id).first()
    if not function:
        return ResponseCode(function_id).response_404()
    return function


@function_router.put("/{function_id}")
async def update_function(function_id: int, function: FunctionIn):
    select_function = await FunctionModel.filter(id=function_id).first()
    select_other_function = await FunctionModel.exclude(id=function_id).filter(en_name=function.en_name).first()
    if not select_function:
        return ResponseCode(function.en_name).response_404()
    if select_other_function:
        return ResponseCode(function.en_name).response_exist()

    await FunctionModel.filter(id=function_id).update(
        zh_name=function.zh_name,
        en_name=function.en_name,
        content=function.content,
        params=function.params,
        updated_at=datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    )
    updated_function = await FunctionModel.filter(id=function_id).first()
    if not updated_function:
        return ResponseCode(function.zh_name).response_404()
    return ResponseCode(f'函数:{function.en_name}').response_update_success()


@function_router.delete("/{function_id}")
async def delete_function(function_id: int):
    deleted_count = await FunctionModel.filter(id=function_id).delete()
    if not deleted_count:
        return ResponseCode(function_id).response_404()
    return ResponseCode(f"{function_id}的函数").response_delete()
